package com.aiwhose.aiwhosewechatplublicaiwhose.utils.message;


import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.ReplyMessageBean;
import com.thoughtworks.xstream.XStream;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Component
public class WXMessageOrdinaryUtil {
    public String createReturnTextMessage(ReplyMessageBean.TextReplyMessage textMessage)  {
        String xmlMessage = createXMLMessage(textMessage);
        return xmlMessage;
    }
    public String createReturnImageMessage(ReplyMessageBean.ImageReplyMessage imageMessage)   {
        String xmlMessage = createXMLMessage(imageMessage);
        return xmlMessage;
    }

    public String createXMLMessage(Object message) {
        // 获取对象的实际类型
        Class<?> messageType = message.getClass();
        try {
            // 通过反射获取对象的方法
            Method getToUserNameMethod = messageType.getMethod("getToUserName");
            Method getFromUserNameMethod = messageType.getMethod("getFromUserName");
            Method setToUserNameMethod = messageType.getMethod("setToUserName", String.class);
            Method setFromUserNameMethod = messageType.getMethod("setFromUserName", String.class);
            Method setCreateTimeMethod = messageType.getMethod("setCreateTime", long.class);

            // 调用对象的方法获取相关信息
            String toUserName = (String) getToUserNameMethod.invoke(message);
            String fromUserName = (String) getFromUserNameMethod.invoke(message);

            // 设置消息的相关信息
            setToUserNameMethod.invoke(message, fromUserName);
            setFromUserNameMethod.invoke(message, toUserName);
            setCreateTimeMethod.invoke(message, new Date().getTime());

            // 使用 XStream 将对象转换为 XML
            XStream xStream = new XStream();
            xStream.processAnnotations(messageType);
            String xmlStr = xStream.toXML(message);
            return xmlStr;
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Failed to create XML message");
        }
    }
}
